/**
 * @file master_process.c
 * @author neozng
 * @brief  module for recv&send vision data
 * @version beta
 * @date 2022-11-03
 * @todo 增加对串口调试助手协议的支持,包括vofa和serial debug
 * @copyright Copyright (c) 2022
 *
 */
#include "master_process.h"
#include "seasky_protocol.h"
#include "daemon.h"
#include "bsp_log.h"
#include "robot_def.h"

static Vision_Recv_s recv_data;
static Vision_Send_s send_data;
static DaemonInstance *vision_daemon_instance;

//中南大学的通信实例，后续考虑将通信进行融合
static uint8_t *rv_vis_recv_buff;        //存储接收到的视觉数据,用来动态分配的缓冲区
static RV_Receive_Packet_s rv_recv_data; //存储接收到的视觉数据包
static RV_Send_Packet_s rv_send_data;    //存储要发送的视觉数据包
static DaemonInstance *rv_vision_daemon_instance;//视觉守护进程的实例
static uint8_t rv_send_buff[sizeof(RV_Send_Packet_s)];//用于存储要发送的视觉数据包的字节表示


//所有设置数据的函数都放在此处
//湖大的
void VisionSetFlag(Enemy_Color_e enemy_color, Work_Mode_e work_mode, Bullet_Speed_e bullet_speed)
{
    send_data.enemy_color = enemy_color;
    send_data.work_mode = work_mode;
    send_data.bullet_speed = bullet_speed;
}

void VisionSetAltitude(float yaw, float pitch, float roll)
{
    send_data.yaw = yaw;
    send_data.pitch = pitch;
    send_data.roll = roll;
}

//中南的
void RVSetAttitude(float yaw, float pitch, float roll)
{
    rv_send_data.yaw = yaw;
    rv_send_data.pitch = pitch;
    rv_send_data.roll = roll;
}

void RVRefreeSetAltitude(uint16_t current_HP,uint16_t stage_remain_time,uint8_t game_status,uint16_t game_progress)
{
    rv_send_data.current_HP = current_HP;
    rv_send_data.stage_remain_time = stage_remain_time;
    rv_send_data.game_status = game_status;
    rv_send_data.game_progress = game_progress;
    // rv_recv_data.RfidStatus = RfidStatus;
}

void RVVisionSetFlag(Enemy_Color_e enemy_color)
{
    rv_send_data.enemy_color = enemy_color;
}



/**
 * @brief 离线回调函数,将在daemon.c中被daemon task调用
 * @attention 由于HAL库的设计问题,串口开启DMA接收之后同时发送有概率出现__HAL_LOCK()导致的死锁,使得无法
 *            进入接收中断.通过daemon判断数据更新,重新调用服务启动函数以解决此问题.
 *
 * @param id vision_usart_instance的地址,此处没用.
 */
static void VisionOfflineCallback(void *id)
{
#ifdef VISION_USE_UART
    USARTServiceInit(vision_usart_instance);
#endif // !VISION_USE_UART
    LOGWARNING("[vision] vision offline, restart communication.");
}

#ifdef VISION_USE_UART

#include "bsp_usart.h"

static USARTInstance *vision_usart_instance;

/**
 * @brief 接收解包回调函数,将在bsp_usart.c中被usart rx callback调用
 * @todo  1.提高可读性,将get_protocol_info的第四个参数增加一个float类型buffer
 *        2.添加标志位解码
 */
static void DecodeVision()
{
    uint16_t flag_register;
    DaemonReload(vision_daemon_instance); // 喂狗
    get_protocol_info(vision_usart_instance->recv_buff, &flag_register, (uint8_t *)&recv_data.pitch);
    // TODO: code to resolve flag_register;
}

Vision_Recv_s *VisionInit(UART_HandleTypeDef *_handle)
{
    USART_Init_Config_s conf;
    conf.module_callback = DecodeVision;
    conf.recv_buff_size = VISION_RECV_SIZE;
    conf.usart_handle = _handle;
    vision_usart_instance = USARTRegister(&conf);

    // 为master process注册daemon,用于判断视觉通信是否离线
    Daemon_Init_Config_s daemon_conf = {
        .callback = VisionOfflineCallback, // 离线时调用的回调函数,会重启串口接收
        .owner_id = vision_usart_instance,
        .reload_count = 10,
    };
    vision_daemon_instance = DaemonRegister(&daemon_conf);

    return &recv_data;
}

/**
 * @brief 发送函数
 *
 * @param send 待发送数据
 *
 */
void VisionSend()
{
    // buff和txlen必须为static,才能保证在函数退出后不被释放,使得DMA正确完成发送
    // 析构后的陷阱需要特别注意!
    static uint16_t flag_register;
    static uint8_t send_buff[VISION_SEND_SIZE];
    static uint16_t tx_len;
    // TODO: code to set flag_register
    flag_register = 30 << 8 | 0b00000001;
    // 将数据转化为seasky协议的数据包
    get_protocol_send_data(0x02, flag_register, &send_data.yaw, 3, send_buff, &tx_len);
    USARTSend(vision_usart_instance, send_buff, tx_len, USART_TRANSFER_DMA); // 和视觉通信使用IT,防止和接收使用的DMA冲突
    // 此处为HAL设计的缺陷,DMASTOP会停止发送和接收,导致再也无法进入接收中断.
    // 也可在发送完成中断中重新启动DMA接收,但较为复杂.因此,此处使用IT发送.
    // 若使用了daemon,则也可以使用DMA发送.
}

#endif // VISION_USE_UART

#ifdef VISION_USE_VCP

#include "bsp_usb.h"
static uint8_t *vis_recv_buff;
//湖大的
static void DecodeVision(uint16_t recv_len)
{
    uint16_t flag_register;
    get_protocol_info(vis_recv_buff, &flag_register, (uint8_t *)&recv_data.pitch);
    //recv_data.target_state = ((flag_register & 0x0f));
    //recv_data.target_type = ((flag_register & 0xf0) >> 4);
    // TODO: code to resolve flag_register;
}
//中南的
#define HEADER_VALUE 0xff
static void RVDecode(uint16_t recv_len)
{

    DaemonReload(rv_vision_daemon_instance);
    if (recv_len < sizeof(RV_Receive_Packet_s))
    {
        LOGERROR("[vision] data length error.");
        return;
    }
    if (rv_vis_recv_buff[0] != HEADER_VALUE)
    {
        LOGERROR("[vision] header error.");
        return; 
    }    
    memcpy(&rv_recv_data, rv_vis_recv_buff, sizeof(RV_Receive_Packet_s));


}
static void RV_VisionOfflineCallback(void *id)
{
    LOGWARNING("[vision] vision offline, restart communication.");
}

/* 视觉通信初始化（湖大） */
// Vision_Recv_s *VisionInit(UART_HandleTypeDef *_handle)
// {
//     UNUSED(_handle); // 仅为了消除警告
//     USB_Init_Config_s conf = {.rx_cbk = DecodeVision};
//     vis_recv_buff = USBInit(conf);

//     // 为master process注册daemon,用于判断视觉通信是否离线
//     Daemon_Init_Config_s daemon_conf = {
//         .callback = VisionOfflineCallback, // 离线时调用的回调函数,会重启串口接收
//         .owner_id = NULL,
//         .reload_count = 50, // 50ms
//     };
//     vision_daemon_instance = DaemonRegister(&daemon_conf);

//     return &recv_data;
// }
/* 视觉通信初始化（中南） */
RV_Receive_Packet_s *RV_VisionInit(UART_HandleTypeDef *_handle)
{
    UNUSED(_handle); 
    USB_Init_Config_s conf = {.rx_cbk = RVDecode};
    rv_vis_recv_buff = USBInit(conf);

    Daemon_Init_Config_s daemon_conf = {
        .callback = RV_VisionOfflineCallback, 
        .owner_id = NULL,
        .reload_count = 50, 
    };
    rv_vision_daemon_instance = DaemonRegister(&daemon_conf);
    rv_send_data.header = 0xff;
    // // rv_send_data.mode = 0;
    // // rv_send_data.reserved = 0;
    // rv_send_data.current_HP = 200;
    // rv_send_data.stage_remain_time = 180 ;
	// rv_send_data.game_status = 1;
	// rv_send_data.game_progress = 1;
    // rv_send_data.cmd_enable = 1;
	// rv_send_data.cmd_x = 75.78;
    // rv_send_data.cmd_y = 114.514;
    rv_send_data.ender = 0x0d;
    return &rv_recv_data;
}
//湖大视觉发送
void VisionSend()
{
    static uint16_t flag_register;
    static uint8_t send_buff[VISION_SEND_SIZE];
    static uint16_t tx_len;
    // TODO: code to set flag_register
    flag_register = 30 << 8 | send_data.enemy_color;
    // 将数据转化为seasky协议的数据包
    get_protocol_send_data(0x02, flag_register, &send_data.yaw, 3, send_buff, &tx_len);
    USBTransmit(send_buff, tx_len);
}

//中南视觉发送
void RV_VisionSend()
{
    memcpy(rv_send_buff, &rv_send_data, sizeof(RV_Send_Packet_s) );
    USBTransmit(rv_send_buff, sizeof(RV_Send_Packet_s));
}



#endif // VISION_USE_VCP
